package services

import (
	"backend/models"

	"gorm.io/gorm"
)

type RoleService struct {
	db *gorm.DB
}

func NewRoleServices(db *gorm.DB) *RoleService {
	return &RoleService{db: db}
}

func (r *RoleService) Create(m *models.Role) error {
	return r.db.Create(m).Error
}

func (r *RoleService) Update(role_id uint, m *models.Role) error {
	return r.db.Where("id = ?", role_id).Updates(m).Error
}

func (r *RoleService) Delete(role_id uint) error {
	return r.db.Where("id = ?", role_id).Delete(&models.Role{}).Error
}

func (r *RoleService) GetList(q *models.PageInfo, m *models.Role) ([]*models.Role, int64, error) {
	var total int64
	var roles []*models.Role
	query := r.db.Model(&models.Role{})
	if m.Name != "" {
		query = query.Where("name = ?", m.Name)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := query.Order("created_at DESC").Limit(q.Size).Offset((q.Page - 1) * q.Size).Find(&roles).Error; err != nil {
		return nil, 0, err
	}
	return roles, total, nil
}

func (r *RoleService) SetRolePermission(role_id uint, permissions []uint) error {
	var role models.Role
	if err := r.db.First(&role, role_id).Error; err != nil {
		return err
	}

	var permissionEntities []models.Permission
	if err := r.db.Where("id IN ?", permissions).Find(&permissionEntities).Error; err != nil {
		return err
	}

	if err := r.db.Model(&role).Association("Permissions").Replace(permissionEntities); err != nil {

		return err
	}
	return nil
}
